package com.tlx.spring.boot.bootstrap.controller;

import com.tlx.spring.boot.bootstrap.entity.User;
import com.tlx.spring.boot.bootstrap.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Optional;


@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public ModelAndView list(Model model) {
        model.addAttribute("title", "用户管理");
        model.addAttribute("userList", userRepository.findAll());
        return new ModelAndView("users/list", "userModel", model);
    }

    @GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") Long id, Model model) {
        Optional<User> users = userRepository.findById(id);
        User user = users.get();
        model.addAttribute("title", "查看用户");
        model.addAttribute("user", user);
        return new ModelAndView("users/view", "userModel", model);
    }

    @GetMapping("/form")
    public ModelAndView view(Model model) {
        model.addAttribute("title", "创建用户");
        model.addAttribute("user", new User(null,null,null));
        return new ModelAndView("users/form", "userModel", model);
    }

    @PostMapping
    public ModelAndView create(User user) {
        user = userRepository.save(user);
        return new ModelAndView("redirect:/users");
    }

    @GetMapping("delete/{id}")
    public ModelAndView delete(@PathVariable("id") Long id, Model model) {
        userRepository.deleteById(id);
        model.addAttribute("title", "删除用户");
        model.addAttribute("userList", userRepository.findAll());
        return new ModelAndView("users/list", "userModel", model);
    }

    @GetMapping("modify/{id}")
    public ModelAndView modifyForm(@PathVariable("id") Long id, Model model) {
        Optional<User> users = userRepository.findById(id);
        User user = users.get();
        model.addAttribute("title", "修改用户");
        model.addAttribute("user", user);
        return new ModelAndView("users/form", "userModel", model);
    }
}
